Ext.extend(avatar.module, {
	init : function() {
        var me = this;
        me.store = new Ext.data.JsonStore({
			fields : ["id", "trackingNumber", "maker.name", "whenOccurred", "usageDelayDays", "quantityOfBlock", "quantityOfColumn"]
		}),
		w_items_ds = new Ext.data.JsonStore({
		    fields : ["product.name", "location.name", "quantityOfColumn", "quantityOfBlock"]
		}),
		location_ds = new Ext.data.JsonStore({
			fields : ["id", "name"]			
		});
        dwr.engine.setAsync(false);
		ProductManager.getAllLocation(function(data){ 
		    location_ds.loadData(data);		    
		});
		dwr.engine.setAsync(true);


	/**	store.on('update', function(self, record){
			var role_filter = Ext.getCmp('party-role-filter');
			var updatedRec =  {id : record.get("id"), name : record.get("name"), 
			                   phoneNumber: record.get('phoneNumber'), 
			                   role : me.getRole(role_filter.selectedIndex), active: record.get('active')}; 	
			PartyManager.saveParty(updatedRec, function(data){			
			    role_filter.fireEvent('select', null, null, role_filter.selectedIndex);
			});

		});
		
		var Party = Ext.data.Record.create([
			{ name: 'name', type: 'string' },
			{ name: 'phoneNumber', type: 'string' }		
		]);
        var WarehousingItem = Ext.data.Record.create([
			{ name: 'productId', type: 'int' },
			{ name: 'quantityOfColumn', type: 'int' },
			{ name: 'quantityOfBlock', type: 'int' }
		]);*/
        var tbar = 
				 [
				 
				 /**'日期范围: ', ' ',
                   new Ext.ux.SelectBox({
                     listClass:'x-combo-list-small',
                     width:93,
                     value:'当天',
                     id:'warehousing-date-range-filter',
                     store: new Ext.data.SimpleStore({
                        fields: ['d'],
                        expandData: true,
                        data : [ '当天','近7天','近30天' ]
                     }),
                     displayField: 'd',
					 listeners: {
                       select: function(self, rec,index){
                       	   me.dateRange = 1;
                           if (index == 1) me.dateRange = 7;
                           if (index == 2) me.dateRange = 30;

                           ProductManager.findRecentWarehousings(me.dateRange, function(data){
								store.loadData(data);
						   });
					   }

					 }
                   }), ' ',*/
                   new Ext.Toolbar.Button({ id: 'warehousing-add-btn', text:'新建', handler : function(){ 				   
				        var maker_ds = new Ext.data.JsonStore({
							fields : ["id", "name", "phoneNumber"]
						}),
						product_ds = new Ext.data.JsonStore({
							fields : ["id", "name"]
						}),
						item_ds = new Ext.data.JsonStore({
							fields : ["productId", "locationId", "quantityOfColumn", "quantityOfBlock"]
						});
						
						product_sm = new Ext.grid.RowSelectionModel({singleSelect:true});

				        PartyManager.getAllActivePartyByRole('maker', function(data){
						    maker_ds.loadData(data);
					    });
					    ProductManager.getAllProduct( function(data){
							product_ds.loadData(data);
						});
						
						var editor = new Ext.ux.grid.RowEditor({
							saveText: '保存',
							cancelText: '取消'
							//clicksToEdit: 2
							
						});
						
						var form_tbar = 
						 [
				           { id: 'product-add-btn', text:'新建', handler : function(){ 				
								var newRec = new Ext.data.Record({productId: product_ds.getAt(0).get('id'), locationId: location_ds.getAt(0).get('id'), quantityOfColumn:0, quantityOfBlock: 0});
								editor.stopEditing();						
								item_ds.insert(0, newRec);
								var grid = Ext.getCmp('new-warehousing-product-grid');
								grid.getView().refresh();
								
								grid.getSelectionModel().selectRow(0);
								editor.startEditing(0);	 
						   } },
						   { id: 'product-remove-btn', text:'删除', handler : function(){					      	 
						   	     var grid = Ext.getCmp('new-warehousing-product-grid');
						   	     var cell = grid.getSelectionModel().getSelected();
						   	     if (cell){
						   	     	editor.stopEditing();
						   	     	item_ds.remove(cell);
						   	     }
						   	
						      }
						   }
						   	
						   ];
		               var form = new Ext.FormPanel({
			                labelWidth: 75, 
		            		frame: true,
							defaults: {anchor: '99%'},
							defaultType: 'textfield', 				
			        		items : [
			        		  {xtype:'combo', fieldLabel:'生产班组', name: 'maker',
			        		     store : maker_ds,
			        		     id: 'warehousing-maker-combo',
						         forceSelection : true,
						         displayField: 'name',
						         valueField:'id',
								 editable:false,
								 typeAhead: true,
								 mode: 'local',
								 triggerAction: 'all',
								 selectOnFocus:true,
								 allowBlank: false		        		  
			        		  } ,
			        		  {xtype:'numberfield', id: 'warehousing-cache-days', fieldLabel:'缓存天数', name: 'usageDelayDays',emptyText : '0', allowNegative : false}
			        		  ,
			        		  {
			        		  	xtype:'grid',
			        		  	id: 'new-warehousing-product-grid',
				                tbar: form_tbar,
								plugins: [editor],
			        		  	store: item_ds,
								sm: product_sm,
								columns:[
					               {
									   header: '产品',
									   dataIndex: 'productId',
									   sortable: true,
									   width: 120,
									   editor: {								
										 xtype: 'combo', 
									     store : product_ds,
								         forceSelection : true,
								         anchor:'-20',
								         displayField: 'name',
								         valueField:'id',
										 editable:false,
										 typeAhead: true,
										 mode: 'local',
										 triggerAction: 'all',
										 selectOnFocus:true,
										 allowBlank: false
									   },
									   renderer: function(val){
									   	   var index = product_ds.findExact('id', val);
									   	   if (index > -1)
									   	       return product_ds.getAt(index).get('name');
									   	   else 
									   	       return '';
									   }
									},
									{
									   header: '仓库位置',  
									   dataIndex: 'locationId',	
									   width: 90,
									   editor: {								
										 xtype: 'combo', 
									     store : location_ds,
								         forceSelection : true,
								         displayField: 'name',
								         valueField:'id',
										 editable:false,
										 typeAhead: true,
										 mode: 'local',
										 anchor:'-20',
										 triggerAction: 'all',
										 selectOnFocus:true,
										 allowBlank: false
									   },
									   renderer: function(val){
									   	   var index = location_ds.findExact('id', val);
									   	   if (index > -1)
									   	       return location_ds.getAt(index).get('name');
									   	   else 
									   	       return '';
									   }
									},
									{
							            xtype: 'numbercolumn',
							            header: '条数',
							            dataIndex: 'quantityOfColumn',
							            width: 55,
							            format: '0',
							            editor: {
							                xtype: 'numberfield',
							                allowDecimals : false
							            }
							        },{
							            xtype: 'numbercolumn',
							            header: '块数',
							            dataIndex: 'quantityOfBlock',
							            width: 55,
							            format: '0',
							            editor: {
							                xtype: 'numberfield',
							                allowDecimals : false
							            }
							        } 
					                
					            ],
								autoWidth: true,
								height:250,
								frame:true,
								clicksToEdit:1			        		  	
			        		  }
			        		],
			        		buttons: [{
			                    text:'提交',
			                    handler: function(){
			                    	
			                    	var pass = form.getForm().isValid();
			                    	if (pass){
			                    		var grid = Ext.getCmp('new-warehousing-product-grid');
			                    		grid.stopEditing();
			                    		var selectedRows = grid.getSelectionModel().getSelections();
			                    		if (item_ds.getCount() == 0){
			                    		    alert("至少需要增加一个产品。")
			                    		    return;
			                    		}
			                    		var items = new Array();

			                    		for (i=0,cnt = item_ds.getCount() ;i<cnt;i+=1){
			                    		    var rec = item_ds.getAt(i);	
			                    		    items[i] = new WarehousingItemDto();
			                    		    items[i].productId = rec.get("productId"); 
			                    		    items[i].locationId = rec.get("locationId");
			                    		    items[i].quantityOfColumn = rec.get("quantityOfColumn");
			                    		    items[i].quantityOfBlock = rec.get("quantityOfBlock");
			                    		    
			                    		 //   confirmItems += "<li>" + rec.get("name") + "(条数:" + items[i].quantityOfColumn
			                    		   //    + ",块数:" + items[i].quantityOfBlock + ")</li>"
			                    		}
			                    		
			                    		
			                    		var makerId = Ext.getCmp('warehousing-maker-combo').getValue(),
			                    		    cacheDays = Ext.getCmp('warehousing-cache-days').getValue();

			                    		ProductManager.saveWarehousingBill(items, makerId, cacheDays, function(data){
											Ext.getCmp('product-in-grid').refresh();

											win.close();
			                    		
			                    		});
			                    	}
			                    }
			                },{
			                    text: '关闭',
			                    handler: function(){
			                        editor.stopEditing();
			                        win.close();
			                    }
			                }]
		               
		               });     	
		               var win =  new Ext.Window({//window config
						    constrain : true,
							layout : 'fit',
							title: '新建入库单',
							width : 400,
							closeAction : 'close',
							height : 390,
							resizable : false,
							shadow : true,
							modal : true,
							closable : true,
							border : false,
							animCollapse : true,
							items : [form]
							
						});
						
						win.show();

				   } }),
				   new Ext.Toolbar.Button({
				       id: 'warehousing-print-btn', text:'打印', disabled: true, handler : function(){
				       	    var record = sm.getSelected();
				       	    if (record){
				       	    	var cacheDay = record.get('usageDelayDays');
				       	        printGrid(Ext.getCmp('warehouse-details-grid'), '入库单 ' + record.get('trackingNumber') , 
				       	        record.get('maker.name'), 
				       	        '总条数:' + record.get('quantityOfColumn') + ' 总块数:' + record.get('quantityOfBlock'));
				       	    }
				       }
				   })
				   
			    ];

        var sm = new Ext.grid.RowSelectionModel({singleSelect:true});
        sm.on('selectionchange', function(sm){	
		    var record = sm.getSelected();
            if (record)
		    ProductManager.getWarehousingById(record.get('id'), function(data){
		        w_items_ds.loadData(data.items);
		    });
		    else
		        w_items_ds.removeAll();
		    
		    Ext.getCmp('warehousing-print-btn').setDisabled(!record);
		    
        });
        
        var queryDto = new QueryDto();
		queryDto.startDate = new Date().format('Y-m-d');
		
		ProductManager.findWarehousings(queryDto, function(data){
			me.store.loadData(data);
		});

		this.tabpanel.add(
		  {	xtype:'panel',
		  	//closable:true,
		  	id: 'product-in-grid',
		  	title: '生产入库单',
		  	border: false,
			layout:'border',

			query : queryDto,
			refresh:function(){
				ProductManager.findWarehousings(this.query, function(data){
					me.store.loadData(data);
				});
			},
			setQuery:function(query){
				this.query = query;
				this.refresh();
			},

			defaults: {
				split: true
			},
			items:[
			{
				xtype:'grid',				
				id: 'warehousing-checkin',
				region: 'center',
				margins: '2 0 2 2',
				store : me.store, 
                tbar: tbar,
                sm: sm,
				columns:[
					new Ext.grid.RowNumberer(),
					{  dataIndex: 'id', hidden: true },
					{
					   header: '单号',
					   dataIndex: 'trackingNumber',
					   sortable: true,
					   width: 100
					},
					{
					   header: '生产班组',
					   dataIndex: 'maker.name',
					   sortable: true,
					   width: 230
					},											
					{   xtype: 'datecolumn',
					    format:'Y-m-d H:i',
						header: '入库日期',
						dataIndex: 'whenOccurred',
						width: 100
					},
					{   xtype: 'numbercolumn',
					    format: '0',
						header: '缓存天数',
						dataIndex: 'usageDelayDays',
						width: 75
					}
					]				
          },
          {     xtype:'grid',
                id:'warehouse-details-grid',
				margins: '30 2 2 2',
				region: 'east',
				store : w_items_ds, 
				width: 350,
				columns:[
					new Ext.grid.RowNumberer(),
					{
					   header: '产品',
					   dataIndex: 'product.name',
					   width: 135
					},
					{
						header: '仓库位置',
						dataIndex: 'location.name',
						width: 75
					},
					{
						header: '条数',
						dataIndex: 'quantityOfColumn',
						width: 50
					},
					{
						header: '块数',
						dataIndex: 'quantityOfBlock',
						width: 50
					}]
          	
          }]
          
          
		  }).show();        
          
	}
});

